package com.part2.action.common;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.actions.DispatchAction;

import com.part2.Constants;
import com.part2.beans.Users;
import com.part2.common.query.Page;

public class CommonAction<T> extends DispatchAction implements Constants {

	private static final Log logger = LogFactory.getLog(CommonAction.class);

	public static final int DEFAULT_PAGE_SIZE = 10;

	protected Users getLoginUser(HttpServletRequest request) throws Exception {
		try {
			return (Users) request.getSession().getAttribute(USER_IN_SESSION);
		} catch (Exception e) {
			logger.error("User is NOT in session!");
			throw new Exception();
		}
	}

	protected String getLoginUserId(HttpServletRequest request)
			throws Exception {

		try {
			return getLoginUser(request).getUserId();
		} catch (Exception e) {
			logger.error("User is NOT in session!");
			throw new Exception();
		}
	}

	protected String getString(String name, HttpServletRequest request) {

		if (request.getParameter(name) != null)
			return request.getParameter(name);

		if (request.getAttribute(name) != null)
			return (String) request.getAttribute(name);

		return null;
	}

	protected Page<T> initPage(HttpServletRequest request, int defaultPageSize) {

		Page<T> page;

		if (StringUtils.isNotEmpty(request.getParameter("pageNo"))) {

			page = new Page<T>();

			String pageNo = request.getParameter("pageNo");
			String pageSize = request.getParameter("pageSize");
			String totalCount = request.getParameter("totalCount");

			try {
				page.setPageNo(Integer.parseInt(pageNo));
				page.setPageSize(Integer.parseInt(pageSize));
				page.setTotalCount(Integer.parseInt(totalCount));
			} catch (Exception e) {
				logger.error("init page exception:" + e);
			}

		} else {
			page = new Page<T>(defaultPageSize);
		}

		return page;
	}

	protected Page<T> initPage(HttpServletRequest request) {
		return initPage(request, DEFAULT_PAGE_SIZE);
	}

}
